package com.example.football;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.hardware.lights.LightState;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.football.entity.Schedule;
import com.example.football.util.JDBCUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class Main2Activity extends AppCompatActivity {


    int cc=0;
    static public Integer peopleid;
    static public String account;
    static public String name;
    static public String byteam;


    public ArrayList<Schedule> list;

    SimpleDateFormat formatter;
    Date curDate;
    String   currentTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null){
            actionBar.hide();
        }


        formatter   =   new   SimpleDateFormat   ("yyyy-MM-dd");
        curDate =  new Date(System.currentTimeMillis());
        currentTime = formatter.format(curDate);
//        BottomNavigationView navView = findViewById(R.id.nav_view);
//        // Passing each menu ID as a set of Ids because each
//        // menu should be considered as top level destinations.
//        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
//                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
//                .build();
//        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
//        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
//        NavigationUI.setupWithNavController(navView, navController);


        Intent intent=getIntent();
        peopleid= intent.getIntExtra("id",0);
        account = intent.getStringExtra("account");
        byteam = intent.getStringExtra("byteam");
        name = intent.getStringExtra("name");

        Log.d("时间", currentTime);

        Toast.makeText(Main2Activity.this, "欢迎你，"+name, Toast.LENGTH_SHORT).show();

        list = new ArrayList<>();

        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("id",peopleid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String url="http://"+ JDBCUtils.ip +":9000/APPpeopleschedule";
        RequestQueue requestQueue= Volley.newRequestQueue(Main2Activity.this);
        JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST, url,jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    JSONArray detail = jsonObject.getJSONArray("detail");
                    for(int i = 0; i < detail.length(); i++){
                        JSONObject data = detail.getJSONObject(i);
                        String s = data.getString("time").substring(0,10)+" "+data.getString("time").substring(11,19);
                        list.add(new Schedule(data.getInt("id"), data.getString("hometeam"), data.getString("guestteam"),
                                    s, data.getString("platform"), data.getString("league")));
                        String s1 = list.get(i).getTime().substring(0,10);
                        if(currentTime.compareTo(s1)==0)
                            sendCounterNotify(list.get(i).getHometeam()+"VS"+list.get(i).getGuestteam(),"时间："+list.get(i).getTime()+"，直播平台:"+list.get(i).getPlatform());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(Main2Activity.this, "网络出错", Toast.LENGTH_SHORT).show();
            }
        });
        requestQueue.add(jsonObjectRequest);


        yuyuesend(byteam);

    }

    public void yuyuesend(String account){
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("team1",account);
            jsonObject.put("team2",account);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String url="http://"+ JDBCUtils.ip +":9000/APPfindyuyuebyteam";
        RequestQueue requestQueue= Volley.newRequestQueue(Main2Activity.this);
        JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST, url,jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    JSONArray detail = jsonObject.getJSONArray("detail");
                    for(int i = 0; i < detail.length(); i++){
                        JSONObject data = detail.getJSONObject(i);
                        if((data.getString("date").equals(currentTime))&&(!data.getString("team1").equals("加入"))&&(!data.getString("team2").equals("加入"))){
                            sendCounterNotify1(data.getString("team1")+"VS"+data.getString("team2"),"时间："+data.getString("date")+" "+data.getString("time")+",场地："+data.getString("site"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(Main2Activity.this, "网络出错", Toast.LENGTH_SHORT).show();
            }
        });
        requestQueue.add(jsonObjectRequest);
    }


    private void sendCounterNotify1(String title, String message) {
        cc++;
        // 发送消息之前要先创建通知渠道，创建代码见MainApplication.java
        // 创建一个跳转到活动页面的意图ite
        Intent clickIntent = new Intent(this, SiteActivity.class);
        // 创建一个用于页面跳转的延迟意图
        PendingIntent contentIntent = PendingIntent.getActivity(this,
                R.string.app_name, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        // 创建一个通知消息的建造器
        Notification.Builder builder = new Notification.Builder(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Android 8.0开始必须给每个通知分配对应的渠道
            builder = new Notification.Builder(this, getString(R.string.app_name+cc));
        }

        builder.setContentIntent(contentIntent) // 设置内容的点击意图
                .setAutoCancel(true) // 点击通知栏后是否自动清除该通知
                .setSmallIcon(R.mipmap.ic_launcher) // 设置应用名称左边的小图标
                .setSubText("预约场地比赛提醒") // 设置通知栏里面的附加说明文本
                // 设置通知栏右边的大图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.footballplat))
                .setContentTitle(title) // 设置通知栏里面的标题文本
                .setContentText(message); // 设置通知栏里面的内容文本
        Notification notify = builder.build(); // 根据通知建造器构建一个通知对象
        // 从系统服务中获取通知管理器
        NotificationManager notifyMgr = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        // 使用通知管理器推送通知，然后在手机的通知栏就会看到该消息
        notifyMgr.notify(R.string.app_name+cc, notify);
    }


    private void sendCounterNotify(String title, String message) {
        cc++;
        // 发送消息之前要先创建通知渠道，创建代码见MainApplication.java
        // 创建一个跳转到活动页面的意图
        Intent clickIntent = new Intent(this, PeoplescheduleActivity.class);
        // 创建一个用于页面跳转的延迟意图
        PendingIntent contentIntent = PendingIntent.getActivity(this,
                R.string.app_name, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        // 创建一个通知消息的建造器
        Notification.Builder builder = new Notification.Builder(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Android 8.0开始必须给每个通知分配对应的渠道
            builder = new Notification.Builder(this, getString(R.string.app_name+cc));
        }

        builder.setContentIntent(contentIntent) // 设置内容的点击意图
                .setAutoCancel(true) // 点击通知栏后是否自动清除该通知
                .setSmallIcon(R.mipmap.ic_launcher) // 设置应用名称左边的小图标
                .setSubText("预定赛程提醒") // 设置通知栏里面的附加说明文本
                // 设置通知栏右边的大图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo))
                .setContentTitle(title) // 设置通知栏里面的标题文本
                .setContentText(message); // 设置通知栏里面的内容文本
        Notification notify = builder.build(); // 根据通知建造器构建一个通知对象
        // 从系统服务中获取通知管理器
        NotificationManager notifyMgr = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        // 使用通知管理器推送通知，然后在手机的通知栏就会看到该消息
        notifyMgr.notify(R.string.app_name+cc, notify);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_tv_schedule:
                Intent intent = new Intent(this,ScheduleActivity.class);
                startActivity(intent);
                break;
            case R.id.main_tv_news:
                intent = new Intent(this,NewActivity.class);
                startActivity(intent);
                break;
            case R.id.main_tv_people:
                intent = new Intent(this,GerenActivity.class);
                startActivity(intent);
                break;
            case R.id.footballyuyue:
                intent = new Intent(this,SiteActivity.class);
                startActivity(intent);
                break;
        }
    }



}
